package top.aylan.org.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.aylan.org.dao.UserMapper;
import top.aylan.org.entity.User;
import top.aylan.org.entity.UserExample;
import top.aylan.org.service.UserService;
import top.aylan.org.tools.Pager;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2018/12/9.
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public User findUserByAccount(String account) throws Exception {

        return userMapper.findUserByAccount(account);
    }

    public User login(String account, String password, HttpServletRequest request) throws  Exception{

        if(account == null || account.equals("")){
            throw new Exception("请输入用户名!");
        }else if(password.equals("") || password == null){
            throw new Exception("请输入密码!");
        }
        User user = findUserByAccount(account);
        if(user == null){
           throw new Exception("用户不存在!");
        }else if(user.getPassword().equals(password)){
            request.getSession().setAttribute("LoginUser",user);
            return user;
        }
        throw new Exception("密码错误!");
    }

    @Override
    public List<User> selectUsersByPage(Pager page) throws Exception {

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();

        int totalRow = userMapper.countByExample(example);
        page.setTotalRow(totalRow);
        if(page.getCurrentPage() > page.getTotalPage()){
            page.setCurrentPage(page.getTotalPage());
        }
        example.setOfset((page.getCurrentPage() - 1) * page.getEveyPageRow());
        example.setSize(page.getEveyPageRow());
        return userMapper.selectByExample(example);
    }

    @Override
    public int delete(Integer id){

        return userMapper.deleteByPrimaryKey(id);
    }
}
